package com.clei.utils.helper;

import com.clei.utils.ByteUtil;

/**
 * byte数组读取器
 *
 * @author Y
 * @date 2022-04-21
 */
public class BytesReader {

    /**
     * byte数组
     */
    private final byte[] bytes;

    /**
     * 当前读取开始位置
     */
    private int position;

    public BytesReader(byte[] bytes) {
        this(bytes, 0);
    }

    public BytesReader(byte[] bytes, int position) {
        this.bytes = bytes;
        this.position = position;
    }

    /**
     * 读取一个
     *
     * @return byte
     */
    public byte read() {
        return this.bytes[this.position++];
    }

    /**
     * 读取n个
     *
     * @param n byte个数
     * @return byte[]
     */
    public byte[] read(int n) {
        byte[] data = new byte[n];
        n = Math.min(n, this.bytes.length - this.position);
        System.arraycopy(this.bytes, this.position, data, 0, n);
        this.position += n;
        return data;
    }

    /**
     * 读取2字节的int
     *
     * @return int
     */
    public int readInt2() {
        return ByteUtil.byte2ToInt(this.read(2));
    }

    /**
     * 读取4字节的int
     *
     * @return int
     */
    public int readInt4() {
        return ByteUtil.byte4ToInt(this.read(4));
    }

    public long readLong8() {
        return ByteUtil.byte8ToLong(this.read(8));
    }

    /**
     * 读取剩余的
     *
     * @return byte[]
     */
    public byte[] readLast() {
        return read(this.bytes.length - this.position);
    }
}